package jfconfig;

/**
 * Created : Mar 7, 2012
 *
 * @author pquiring
 */

import java.util.*;
import java.io.*;
import javax.swing.*;

import javaforce.*;

public class GroupsPanel extends javax.swing.JPanel {

  /**
   * Creates new form GroupsPanel
   */
  public GroupsPanel() {
    initComponents();
    loadGroups();
    loadUsers();
  }

  /**
   * This method is called from within the constructor to initialize the form.
   * WARNING: Do NOT modify this code. The content of this method is always
   * regenerated by the Form Editor.
   */
  @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {

    jToolBar1 = new javax.swing.JToolBar();
    back = new javax.swing.JButton();
    addGroup = new javax.swing.JButton();
    deleteGroup = new javax.swing.JButton();
    jSplitPane1 = new javax.swing.JSplitPane();
    jScrollPane1 = new javax.swing.JScrollPane();
    groups = new javax.swing.JList();
    jTabbedPane1 = new javax.swing.JTabbedPane();
    jPanel2 = new javax.swing.JPanel();
    jScrollPane2 = new javax.swing.JScrollPane();
    members = new javax.swing.JList();
    addUserCombo = new javax.swing.JComboBox();
    addUser = new javax.swing.JButton();
    removeUser = new javax.swing.JButton();

    jToolBar1.setFloatable(false);
    jToolBar1.setRollover(true);

    back.setText("<Back");
    back.setFocusable(false);
    back.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    back.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    back.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        backActionPerformed(evt);
      }
    });
    jToolBar1.add(back);

    addGroup.setText("Add Group");
    addGroup.setFocusable(false);
    addGroup.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    addGroup.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    addGroup.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        addGroupActionPerformed(evt);
      }
    });
    jToolBar1.add(addGroup);

    deleteGroup.setText("Delete Group");
    deleteGroup.setFocusable(false);
    deleteGroup.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    deleteGroup.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    deleteGroup.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        deleteGroupActionPerformed(evt);
      }
    });
    jToolBar1.add(deleteGroup);

    jSplitPane1.setDividerLocation(164);

    groups.setModel(groupsModel);
    groups.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
    groups.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
      public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
        groupsValueChanged(evt);
      }
    });
    jScrollPane1.setViewportView(groups);

    jSplitPane1.setLeftComponent(jScrollPane1);

    members.setModel(membersModel);
    members.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
    jScrollPane2.setViewportView(members);

    addUser.setText("Add User");
    addUser.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        addUserActionPerformed(evt);
      }
    });

    removeUser.setText("Remove User");
    removeUser.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        removeUserActionPerformed(evt);
      }
    });

    javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
    jPanel2.setLayout(jPanel2Layout);
    jPanel2Layout.setHorizontalGroup(
      jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(jPanel2Layout.createSequentialGroup()
        .addContainerGap()
        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 827, Short.MAX_VALUE)
          .addGroup(jPanel2Layout.createSequentialGroup()
            .addComponent(addUserCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(addUser)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(removeUser)
            .addGap(0, 655, Short.MAX_VALUE)))
        .addContainerGap())
    );
    jPanel2Layout.setVerticalGroup(
      jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(jPanel2Layout.createSequentialGroup()
        .addContainerGap()
        .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 352, Short.MAX_VALUE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(addUserCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(addUser)
          .addComponent(removeUser))
        .addContainerGap())
    );

    jTabbedPane1.addTab("Members", jPanel2);

    jSplitPane1.setRightComponent(jTabbedPane1);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
    this.setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
      .addComponent(jSplitPane1)
    );
    layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jSplitPane1))
    );
  }// </editor-fold>//GEN-END:initComponents

  private void groupsValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_groupsValueChanged
    int idx = groups.getSelectedIndex();
    if (idx == -1) return;
    loadGroup(idx);
  }//GEN-LAST:event_groupsValueChanged

  private void addUserActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addUserActionPerformed
    int idx = groups.getSelectedIndex();
    if (idx == -1) return;
    String userName = (String)addUserCombo.getSelectedItem();
    if (userName == null) return;
    ShellProcess sp = new ShellProcess();
    ArrayList<String> cmd = new ArrayList<String>();
    cmd.add("sudo");
    cmd.add("usermod");
    cmd.add("-a");  //append group
    cmd.add("-G");
    cmd.add((String)groupsModel.getElementAt(idx));
    cmd.add(userName);
    String output = sp.run(cmd, false);
    if (output == null) {
      JFAWT.showError("Error", "Failed to add user to group.");
      return;
    }
    loadGroups();
    groups.setSelectedIndex(idx);
  }//GEN-LAST:event_addUserActionPerformed

  private void removeUserActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeUserActionPerformed
    int idx = groups.getSelectedIndex();
    if (idx == -1) return;
    String userName = (String)members.getSelectedValue();
    if (userName == null) return;
    ShellProcess sp = new ShellProcess();
    ArrayList<String> cmd = new ArrayList<String>();
    cmd.add("sudo");
    cmd.add("usermod");
    cmd.add("-G");
    cmd.add(getUserGroups(userName, idx));
    cmd.add(userName);
    String output = sp.run(cmd, false);
    if (output == null) {
      JFAWT.showError("Error", "Failed to remove user from group.");
      return;
    }
    loadGroups();
    groups.setSelectedIndex(idx);
  }//GEN-LAST:event_removeUserActionPerformed

  private void backActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_backActionPerformed
    ConfigApp.setPanel(new MainPanel());
  }//GEN-LAST:event_backActionPerformed

  private void addGroupActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addGroupActionPerformed
    addGroup();
  }//GEN-LAST:event_addGroupActionPerformed

  private void deleteGroupActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteGroupActionPerformed
    delGroup();
  }//GEN-LAST:event_deleteGroupActionPerformed

  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JButton addGroup;
  private javax.swing.JButton addUser;
  private javax.swing.JComboBox addUserCombo;
  private javax.swing.JButton back;
  private javax.swing.JButton deleteGroup;
  private javax.swing.JList groups;
  private javax.swing.JPanel jPanel2;
  private javax.swing.JScrollPane jScrollPane1;
  private javax.swing.JScrollPane jScrollPane2;
  private javax.swing.JSplitPane jSplitPane1;
  private javax.swing.JTabbedPane jTabbedPane1;
  private javax.swing.JToolBar jToolBar1;
  private javax.swing.JList members;
  private javax.swing.JButton removeUser;
  // End of variables declaration//GEN-END:variables

  private class ListModel extends DefaultListModel {
    public ArrayList<String[]> fields = new ArrayList<String[]>();
  }

  private ListModel groupsModel = new ListModel(), membersModel = new ListModel();

  private void loadGroups() {
    groupsModel.clear();
    groupsModel.fields.clear();
    try {
      FileInputStream fis = new FileInputStream("/etc/group");
      int len = fis.available();
      byte buf[] = new byte[len];
      int pos = 0;
      while (pos < len) {
        int read = fis.read(buf, pos, len-pos);
        if (read <= 0) throw new Exception("file error");
        pos += read;
      }
      fis.close();
      String group = new String(buf);
      String lns[] = group.split("\n");
      for(int a=0;a<lns.length;a++) {
        String f[] = lns[a].split(":", -1);
        //0=group : 1=x : 2=gid : 3=users
        String u[] = f[3].split(",");
        groupsModel.addElement(f[0]);
        groupsModel.fields.add(f);
      }
    } catch (Exception e) {
      JFLog.log(e);
    }
    groups.repaint();
  }

  private void loadGroup(int idx) {
    membersModel.clear();
    if (idx == -1) return;
    String groupMembers[] = groupsModel.fields.get(idx)[3].split(",");
    for(int a=0;a < groupMembers.length;a++) {
      membersModel.addElement(groupMembers[a]);
    }
    members.repaint();
  }

  private void loadUsers() {
    addUserCombo.removeAllItems();
    try {
      FileInputStream fis = new FileInputStream("/etc/passwd");
      int len = fis.available();
      byte buf[] = new byte[len];
      int pos = 0;
      while (pos < len) {
        int read = fis.read(buf, pos, len-pos);
        if (read <= 0) throw new Exception("file error");
        pos += read;
      }
      fis.close();
      String passwd = new String(buf);
      String lns[] = passwd.split("\n");
      for(int a=0;a<lns.length;a++) {
        String f[] = lns[a].split(":", -1);
        //0=user : 1=x : 2=uid : 3=gid : 4=comment : 5=home : 6=shell
        if (f[0].equals("root")) continue;
        if (!f[6].equals("/bin/bash")) continue;
        addUserCombo.addItem(f[0]);
      }
    } catch (Exception e) {
      JFLog.log(e);
    }
  }

  /** Returns groups that user is in, excluding gidx.*/
  private String getUserGroups(String userName, int gidx) {
    StringBuffer out = new StringBuffer();
    for(int a=0;a<groupsModel.size();a++) {
      if (a == gidx) continue;  //exclude deleted one
      String f[] = groupsModel.fields.get(a);
      boolean ok = false;
      for(int b=0;b<f.length;b++) {
        if (f[b].equals(userName)) {ok = true; break;}
      }
      if (ok) {
        if (out.length() > 0) out.append(",");
        out.append((String)groupsModel.getElementAt(a));
      }
    }
    return out.toString();
  }

  private void addGroup() {
    String name = JFAWT.getString("Enter group name", "");
    if ((name == null) || (name.trim().length() == 0)) return;
    name = name.trim();
    ShellProcess sp = new ShellProcess();
    ArrayList<String> cmd = new ArrayList<String>();
    cmd.add("sudo");
    cmd.add("groupadd");
    cmd.add(name);
    String output = sp.run(cmd, false);
    if (output == null) {
      JFAWT.showError("Error", "Failed to exec groupadd.");
    }
    loadGroups();
  }

  private void delGroup() {
    int idx = groups.getSelectedIndex();
    if (idx == -1) return;
    String name = (String)groupsModel.getElementAt(idx);
    if (!JFAWT.showConfirm("Confirm", "Are you sure you want to delete group '" + name + "'?")) return;
    ShellProcess sp = new ShellProcess();
    ArrayList<String> cmd = new ArrayList<String>();
    cmd.add("sudo");
    cmd.add("groupdel");
    cmd.add(name);
    String output = sp.run(cmd, false);
    if (output == null) {
      JFAWT.showError("Error", "Failed to exec groupdel.");
    }
    loadGroups();
  }
}
